package com.kingbook.core.scripting;

import com.kingbook.common.utils.CollectionUtils;
import com.kingbook.common.utils.NumberUtils;
import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.cache.CacheConfig;
import com.kingbook.core.scripting.nodes.SegmentNode;
import com.kingbook.core.scripting.nodes.SqlNode;
import com.google.common.collect.Maps;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
public class SqlTemplate {

    private static Logger logger = LoggerFactory.getLogger(SqlTemplate.class);

    private String namespace;

    private CacheConfig cacheConfig;

    private Map<String, SqlNode> sqlNodeMap = Maps.newHashMap();

    private Map<String, SegmentNode> segmentNodeMap = Maps.newHashMap();

    SqlTemplate(Element rootElement) {
        Element mapper = rootElement.getChildren().get(0);
        namespace = mapper.getAttributeValue("namespace");
        cacheConfig = new CacheConfig();
        String useCacheStr = mapper.getAttributeValue("useCache");
        if (StringUtils.isNotEmpty(useCacheStr) && "true".equalsIgnoreCase(useCacheStr)) {
            cacheConfig.setUseCache(true);
            String cacheMaxSizeStr = mapper.getAttributeValue("cacheMaxSize");
            if (StringUtils.isNotEmpty(cacheMaxSizeStr) && NumberUtils.isNumeric(cacheMaxSizeStr)) {
                cacheConfig.setCacheMaxSize(Integer.parseInt(cacheMaxSizeStr));
            }
            String cacheDurationStr = mapper.getAttributeValue("cacheDuration");
            if (StringUtils.isNotEmpty(cacheDurationStr) && NumberUtils.isNumeric(cacheDurationStr)) {
                cacheConfig.setCacheDuration(Integer.parseInt(cacheDurationStr));
            }
        }
        List<Element> list = mapper.getChildren();
        list.forEach(e -> {
            if("segment".equals(e.getName()))
                segmentNodeMap.put(e.getAttributeValue("id"), new SegmentNode(e));
            if("sql".equals(e.getName()))
                sqlNodeMap.put(e.getAttributeValue("id"), new SqlNode(namespace, e, cacheConfig));
        });
    }

    public String getNamaspace() {
        return namespace;
    }

    public Map<String, SqlNode> getSqlNodeMap() {
        return sqlNodeMap;
    }

    public void setSqlNodeMap(Map<String, SqlNode> sqlNodeMap) {
        this.sqlNodeMap = sqlNodeMap;
    }

    public Map<String, SegmentNode> getSegmentNodeMap() {
        return segmentNodeMap;
    }

    public void setSegmentNodeMap(Map<String, SegmentNode> segmentNodeMap) {
        this.segmentNodeMap = segmentNodeMap;
    }
}
